package com.hup.sidebar.androidService;

import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.hup.sidebar.R;
import com.hup.sidebar.SideBarApplication;
import com.hup.sidebar.constant.AppConstant;
import com.hup.sidebar.service.ActivationFloaterService;
import com.hup.sidebar.view.MainActivity;

/**
 * 本app的安卓服务,功能:
 * .悬浮窗服务: {@link ActivationFloaterService}
 * .前台服务:实现app被杀后/app出现异常强退后(由系统)自动重启服务
 * <p>
 * 资料:
 * https://www.cnblogs.com/renhui/p/8575299.html
 * 权限:
 * <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
 *
 * @author hugan
 * @date 2022/6/6
 */
public class AppService extends Service {
    private static final String TAG = AppService.class.getSimpleName();
    private static final int NOTI_ID_TEMP_HIDE = 10001;

    private ActivationFloaterService floaterService;

    /**
     * 切换服务状态
     */
    public static void switchService(boolean isStart) {
        Log.i(TAG, "switchService: " + isStart);
        if (isStart) {
            SideBarApplication.executeIfExist(AppService.class, Service::stopSelf);//不会发生的?
            Context context = SideBarApplication.getContext();
            Intent intent = new Intent(context, AppService.class);
            if (VERSION.SDK_INT >= VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
            //移除[临时关闭]的通知
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancel(NOTI_ID_TEMP_HIDE);
        } else {
            boolean ifExist = SideBarApplication.executeIfExist(AppService.class, Service::stopSelf);
            if (!ifExist) {
                //极快速点击按钮时会发生
                SideBarApplication.onFloaterStarted(false);
            }
        }
    }

    /**
     * 临时关闭
     */
    public void doTempHide() {
        switchService(false);
        //创建[恢复通知]
        Builder builder;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            String notificationChannelId = getClass().getName() + "_2";
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            NotificationChannel channel = new NotificationChannel(notificationChannelId, "[临时关闭]通知",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);

            builder = new Builder(getApplicationContext(), notificationChannelId);
        } else {
            builder = new Builder(getApplicationContext());
        }

        Intent intent = new Intent(SideBarApplication.getContext(), AppBroadcastReceiver.class);
        intent.setAction(AppConstant.ACTION_TEMP_HIDE_NOTI_CLICK);

        PendingIntent contentIntent = PendingIntent.getBroadcast(SideBarApplication.getContext(), 0, intent, 0);
        Notification notification = builder
                .setContentTitle(getString(R.string.temp_hide_noti_title))//标题
                .setSmallIcon(R.mipmap.ic_launcher)//必须有,否则不显示通知!
                .setWhen(System.currentTimeMillis())//通知时间
                .setContentText(getString(R.string.temp_hide_noti_content))
                .setContentIntent(contentIntent)
                .setOngoing(true)
                .build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTI_ID_TEMP_HIDE, notification);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
        initForegroundService();
        SideBarApplication.putBean(this);
        SideBarApplication.onFloaterStarted(true);
        floaterService = new ActivationFloaterService(this);
        floaterService.switchService(true);
    }

    private void initForegroundService() {
        Log.d(TAG, "initForegroundService: ");

        Builder builder;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //要先创建channel
            String notificationChannelId = getClass().getName();
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            NotificationChannel channel = new NotificationChannel(notificationChannelId, "悬浮窗应用的必要通知",
                    //NotificationManager.IMPORTANCE_HIGH);//有震动/声音
                    NotificationManager.IMPORTANCE_NONE);//无震动/声音/收纳,最终决定权是用户的设置(提醒/静默/收纳等,按具体系统而定)
            notificationManager.createNotificationChannel(channel);

            builder = new Builder(getApplicationContext(), notificationChannelId);
        } else {
            builder = new Builder(getApplicationContext());
        }

        /*
        创建常驻通知
        flyme:
            bug: 图标可能更新不及时,变成了'缺省app图标/或首次安装时的图标'
            如果app无通知权限,则由系统通知代替"xxxApp正在显示"
         */
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 12, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification notification = builder
                .setContentTitle(getString(R.string.floater_started))//标题
                .setSmallIcon(R.mipmap.ic_launcher)//必须有,否则不显示通知!
                .setWhen(System.currentTimeMillis())//通知时间
                .setContentText(getString(R.string.floater_goto_launcher))
                .setContentIntent(contentIntent)
                .build();

        startForeground(1, notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: ");
        floaterService.switchService(false);
        stopForeground(true);
        super.onDestroy();
        SideBarApplication.onFloaterStarted(false);
        SideBarApplication.removeBean(this.getClass());
    }

    public void switchFloaterService(boolean b) {
        floaterService.switchService(b);
    }

    public boolean showingFloater() {
        return floaterService.isShowing();
    }

}
